<template>
	<view class="content">
		<textarea class="textareas" maxlength="-1" v-model="searchData.codes" :confirm-hold="true" confirm-type="return"
			placeholder="请输入柜号，多个编码之间以换行拼接，禁止输入特殊字符！最多30个设备号" placeholder-style="font-size:28rpx" :rows="6"
			@change.native="keyUp($event)" @input.native="keyInput($event)"></textarea>
		<view class="search_btns">
			<button type="primary" size="mini" @click="doSearch">搜索</button>
		</view>
		<uni-card :isFull="true" class="parts">
			<text class="head-title">
				查询部件
			</text>
			<checkbox-group @change="partCheckChange" class="check-list">
				<label v-for="(item,index) in partOption" :key="index">
					<checkbox class="part_check" :value="item.code" />{{item.name}}
				</label>
			</checkbox-group>
		</uni-card>

		<view class="search_btns">
			<button type="primary" size="mini" @click="isSearchVersion()">批量查询版本</button>
		</view>
		<view class="table-title" v-if="nofoundList.length>0" style="color: red;">
			未搜索到的设备列表
		</view>
		<uni-list class="nofoundList" v-if="nofoundList.length>0">
			<uni-list-item title="编码">
				<template slot="footer">
					<text style="font-size: 24rpx;">复制</text>
				</template>
			</uni-list-item>
			<uni-list-item v-for="(item,index) in nofoundList" :key="index" :title="item">
				<template slot="footer">
					<text class="iconfont icon-copy" @click="isCopy(item)"></text>
				</template>
			</uni-list-item>
		</uni-list>
		<view class="table-title">
			<view class="head-title">柜列表 <span class="isAllow" v-if="tableData.length>0">（选中设备即为当前页设备）</span></view>
			<view v-if="tableData.length>0" class="isAllow tips">注：设备编码为红色文字的代表当前设备不可用</view>
		</view>
		<view class="table" v-if="tableData.length>0">
			<view class="tr">
				<view class="th">
					<checkbox value="0" style="transform:scale(0.85)" :checked="isCheckedAll" @click="checkAll" />
				</view>
				<view class="th width-text"></view>
				<view class="th"></view>
				<view class="th width-text">操作</view>
			</view>
			<view class="tr" v-for="(item,index) in tableData" :key="index">
				<view class="td indexs">
					<checkbox :value="index+1" :checked="item.checked" style="transform:scale(.85)"
						@click="checkboxClick(index)" />
				</view>

				<view class="td width-text">
					<view>序号</view>
					<view class="bordert">编码</view>
					<view class="bordert">ID</view>
					<view class="bordert indexs">版本</view>
				</view>
				<view class="td">
					<view>{{index+1}}</view>
					<view :class="[{'isAllow':!item.isAllowOperate},'bordert']">{{item.code?item.code:"无"}}</view>
					<view class="bordert">{{item.id}}</view>
					<view class="versions bordert">{{item.equipSoftwareVersions|formatVersion}}</view>
				</view>
				<view class="td width-text operate-icon indexs">
					<view class="iconfont icon-copy" v-if="item.code" @click="isCopy(item.code)"></view>
					<view>
						<uni-icons v-if="item.code && item.isAllowOperate"  type="search" size="24" color="#999999"
							@click="isSearchVersion(index,item.code)"></uni-icons>
					</view>
				</view>
			</view>
		</view>
		<uni-pagination class="pagination" v-if="tableData.length>0" @change="changePage()" :pageSize="size"
			:current="page" :total="total" :show-icon="true" prev-text="前一页" next-text="后一页" />

		<view class="nodata" v-if="tableData.length == 0">
			<image class="empty_img" src="/static/images/empty.png" mode="widthFix"></image>
			<view>暂无数据</view>
		</view>
	</view>
</template>

<script>
	import {
		equipment,
		partType
	} from "@/api/my.js";
	import {
		removeNullUndefined,
		doCopy,
		unique
	} from "@/common/index.js";
	import {
		mapState,
	} from 'vuex';
	export default {
		data() {
			return {
				searchData: {
					codes: "",
				},
				tableData: [],
				// 每页数据量
				size: 30,
				// 当前页
				page: 1,
				total: 0,

				partOption: [], //部件
				versionCodes: [], //查询版本codes
				partTypes: [], //部件
				isCheckedAll: false, //全选
				nofoundList: [], //未找到code列表
			}
		},
		filters: {
			formatVersion(arr) {
				if (arr && arr.length > 0) {
					let arrayTwo = Object.values(
						arr.reduce((res, item) => {
							res[item.partType] ?
								res[item.partType].push(item) :
								(res[item.partType] = [item]);
							return res;
						}, {})
					);
					let jsons = "";
					arrayTwo.map((item, index) => {
						jsons += item[0].partTypeName;
						item.filter((qq, inx) => {
							jsons += qq.version;
							if (inx < item.length - 1) jsons += " | ";
						});
						if (index < arrayTwo.length - 1) jsons += "；";
					});
					return jsons;
				} else {
					return "";
				}
			}
		},
		computed: {
			...mapState(['equipTypeCode'])
		},
		onLoad() {
			this.getPartType();
		},
		methods: {
			getDataList() {
				this.$Toast.loading('加载中~');
				let param = {
					...this.searchData
				};
				if (param.codes) {
					param.codes = param.codes.split("\n").filter(item => item);
				}
				if (param.codes.length == 1) {
					param.code = param.codes[0];
					delete param.codes;
				}

				this.nofoundList = [];
				if (param.codes && param.codes.length > 30) {
					this.$Toast.none('最多30个设备号～');
					return;
				}
				equipment('/version/list', 'post', {
					...removeNullUndefined(Object.assign(param, {
						pageNum: this.page,
						pageSize: this.size,
					}))
				}).then(res => {
					if (res.code == 200) {
						this.tableData = res.data;
						this.tableData.forEach(item => item.checked == false);
						this.total = +res.total;

						// 查找未搜索到的设备code
						if (param.codes) {
							this.nofoundList = param.codes.filter(item => !this.tableData.some(ele => ele.code
								.toLowerCase() ==
								item.toLowerCase()));
						} else if (param.code) {
							this.nofoundList = this.tableData.length == 0 ? [param.code] : [];
						}
					}
				}).finally(() => uni.hideLoading());
			},
			// 分页
			changePage(e) {
				this.page = e.current;
				this.getDataList();
			},
			// 获取部件
			getPartType() {
				partType(`/list?equipTypeCode=${this.equipTypeCode}`, 'get').then(res => {
					if (res.code == 200) {
						this.partOption = res.data;
					}
				});
			},
			// 搜索
			doSearch() {
				let param = {
					...this.searchData
				};

				if (param.codes) {
					param.codes = param.codes.split("\n").filter(item => item);
				}
				if (param.codes.length == 0) {
					this.$Toast.none('请输入柜号');
					return;
				}
				this.getDataList();
			},
			// 复制
			isCopy(item) {
				doCopy(item);
			},
			//限制输入特殊字符
			keyUp(e) {
				let str = e.target.value.replace(
					/[`~!@#$%^&*()_\-+=<>?:"{}|.\;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘’，。、]/g,
					""
				);
				e.target.value = str;
				this.searchData.codes = str;
			},
			// 只能输入汉字、英文、数字
			keyInput(e) {
				let str = e.target.value.replace(/[^\a-\z\A-\Z0-9\n/]/g, "");
				e.target.value = str;
				this.searchData.codes = str;
			},
			partCheckChange(e) {
				this.partTypes = e.detail.value;
			},
			// 查询版本
			isSearchVersion(index, e) {
				if (e) {
					this.versionCodes = [e];
				} else {
					this.versionCodes = this.tableData.filter(item => item.checked).map(p => {
						return p.code
					});
				}
				let onlineList = this.tableData.filter(item => item.checked && item.isAllowOperate); //可操作设备

				if (this.tableData.length == 0) {
					this.$Toast.none('暂无设备，请先搜索~');
					return;
				} else if (this.partTypes.length == 0) {
					this.$Toast.none('请选择部件类型');
					return;
				} else if (this.versionCodes.length == 0) {
					this.$Toast.none('请勾选需要查询的设备');
					return;
				}
				else if (this.versionCodes.length > 0 && onlineList.length == 0) {
					this.$Toast.none('设备离线/禁用不可操作！');
					return;
				}
				if (e) {
					this.checkboxClick(index, true);
				}
				let that = this;
				let msg = '';
				if (onlineList.length < this.versionCodes.length) { //选中设备包含离线
					msg = "离线/禁用设备不可操作，已自动过滤！"
				}
				uni.showModal({
					title: '提示',
					content: this.versionCodes.length > 1 ? `${msg}确定要批量查询版本吗？` : `${msg}确定要查询版本吗？`,
					success(res) {
						if (res.confirm) {
							that.doSearchUpdate();
						}
					}
				})
			},
			doSearchUpdate() {
				this.$Toast.loading('查询中~');
				let equipIds = this.tableData.filter(item => item.checked && item.isAllowOperate).map(p => {
					return p.id
				});
				equipment(`/version/all?ids=${equipIds.join(',')}&partTypes=${this.partTypes.join(',')}`, 'post').then(
					res => {
						if (res.code == 200) {
							let datas = res.data;
							if (datas && datas.length > 0) {
								datas.forEach(item => {
									this.tableData.forEach((pp, inx) => {
										if (item.code == pp.code) {
											this.$set(this.tableData[inx], 'equipSoftwareVersions',
												item.equipSoftwareVersions);
										}
									})
								})
							}
						}
					}).finally(() => uni.hideLoading())
			},
			checkboxClick(e, type) {
				if (type) {
					this.tableData.forEach(item => item.checked = false);
					this.tableData[e].checked = true;
				} else {
					this.tableData[e].checked = !this.tableData[e].checked;
				}
				let checkList = this.tableData.filter(item => item.checked);
				if (checkList.length == this.tableData.length) {
					this.isCheckedAll = true;
				} else {
					this.isCheckedAll = false;
				}
			},
			checkAll() {
				this.isCheckedAll = !this.isCheckedAll;
				if (this.isCheckedAll) {
					this.tableData.forEach(item => item.checked = true);
				} else {
					this.tableData.forEach(item => item.checked = false);
				}
			},
		},
	}
</script>

<style lang="scss" scoped>
	@import "@/static/css/common.scss";
	@import "@/static/iconfont.css";
	@import "@/static/css/main.scss";

	.content {
		padding: 10rpx 20rpx;
		box-sizing: border-box;
	}

	.search_btns {
		text-align: right;
		margin: 10rpx 0 0;

		button {
			background-color: #51b7b9;
		}
	}

	.textareas {
		box-sizing: border-box;
		width: 100%;
		border: 2rpx solid #E5E5E5;
		padding: 10rpx;
		word-break: break-all;
		word-wrap: break-word;
	}

	.part_check {
		transform: scale(0.7);
	}

	.parts {
		color: #333333;
		font-size: 28rpx;

		text {
			display: inline-block;
			line-height: 48rpx;
		}

		::v-deep .uni-card {
			padding: 0 !important;
		}

		::v-deep .uni-card .uni-card__content {
			padding: 8rpx 0 0 !important;
		}

		.check-list {
			@include flexLayout(center, flex-start);
			flex-wrap: wrap;

			label {
				margin: 6rpx;
			}
		}
	}

	.table-title {
		margin: 20rpx 0;
		color: #333333;
		font-size: 32rpx;
		font-weight: 500;
	}

	.table {
		width: 100%;
		border-radius: 8rpx;
		display: table;
		border: 1px solid #dfdfdf;
		border-collapse: collapse;
		color: #333333;
		font-size: 28rpx;
		margin-bottom: 120rpx;
	}

	.th {
		text-align: center;
		padding: 10rpx 0;
		font-weight: bolder;
		display: table-cell;
		border: 1px solid #dfdfdf
	}

	.td {
		text-align: center;
		background: #FFFFFF;
		padding: 10rpx 0;
		display: table-cell;
		border: 1px solid #dfdfdf;

		view {
			min-height: 50rpx;
		}
	}

	.tr {
		display: table-row;
	}

	.indexs {
		vertical-align: middle;
	}

	.width-text {
		width: 76rpx;
	}

	.versions {
		padding: 0 10rpx;
		text-align: left;
	}

	.bordert {
		border-top: 2rpx solid #dfdfdf;
		padding-top: 10rpx;
		margin-top: 10rpx;
	}

	.nodata {
		margin-top: 30%;
	}

	/deep/ .uni-list-item__container {
		padding: 16rpx 20rpx;
	}

	.isAllow {
		color: red;
	}

	.tips {
		font-size: 28rpx;
		margin-top: 10rpx;
	}

	.pagination {
		width: 100%;
		position: fixed;
		bottom: 20rpx;
		left: 0;
		background: #FFFFFF;
		padding: 20rpx 0;
	}

	.icon-copy {
		font-size: 36rpx;
		color: #666666;
	}
</style>